package com.weilx959.spt.plugin.e2sp.utils;

import com.weilx959.spt.plugin.e2sp.constant.ExcelToSqlConstants;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串util
 *
 * @author weilx
 * @since 2024-05-21
 */
public class StringUtil {
    private static final String REGEX = "\\$\\{\\w+}";

    private StringUtil() {
        // private constructor
    }

    /**
     * 格式化字符串
     *
     * @param template 样板
     * @param params   params
     * @return {@link String}
     */
    public static String format(String template, Map<String, String> params) {
        if (StringUtils.isBlank(template) || MapUtils.isEmpty(params)) {
            return template;
        }
        Matcher matcher = Pattern.compile(REGEX).matcher(template);
        StringBuilder sb = new StringBuilder();

        while (matcher.find()) {
            String group = matcher.group();
            String value = params.get(group.substring(2, group.length() - 1));
            matcher.appendReplacement(sb, StringUtils.isBlank(value) ? StringUtils.EMPTY : value);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String convert(Object obj) {
        if (obj == null) {
            return StringUtils.EMPTY;
        }
        if (obj instanceof Time time) {
            return new SimpleDateFormat(ExcelToSqlConstants.TIME_FORMAT).format(time);
        }
        if (obj instanceof Timestamp timestamp) {
            return new SimpleDateFormat(ExcelToSqlConstants.TIMESTAMP_FORMAT).format(timestamp);
        }
        if (obj instanceof java.sql.Date date) {
            return new SimpleDateFormat(ExcelToSqlConstants.DATE_FORMAT).format(date);
        }
        if (obj instanceof Date date) {
            return new SimpleDateFormat(ExcelToSqlConstants.TIMESTAMP_FORMAT).format(date);
        }
        if (obj instanceof LocalDate localDate) {
            return localDate.format(DateTimeFormatter.ofPattern(ExcelToSqlConstants.DATE_FORMAT));
        }
        if (obj instanceof LocalDateTime localDateTime) {
            return localDateTime.format(DateTimeFormatter.ofPattern(ExcelToSqlConstants.TIMESTAMP_FORMAT));
        }
        return obj.toString();
    }

}
